//
//  JWTAlipayChargeView.m
//  JWT
//
//  Created by ndm on 17/2/12.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "JWTAlipayChargeView.h"
#import "JWTCardTypeView.h"
#import <AlipaySDK/AlipaySDK.h>


@interface JWTAlipayChargeView ()

@property (nonatomic,strong) NSArray *cardTypeArray;

@property (nonatomic,strong) JWTCardType *selCardType;

@end

@implementation JWTAlipayChargeView

SHARED_INSTANCE_IMPLEMENTATION(JWTAlipayChargeView);

-(instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame] ;
    if (self) {
        //
        _cardTypeArray = [[NSArray alloc] init];
        _userInfoView = [[UIView alloc] init];
        _userInfoView.backgroundColor = RGB_WhiteBackGround;
        [self addSubview:_userInfoView];
        
        _userImageView = [[UIImageView alloc]initWithFrame:CGRectMake(Cell_Margin*2, Cell_Margin*2, 80, 80)];
        [_userImageView setImage:[UIImage imageNamed:ImageViewDefault]];
        [self addSubview:_userImageView];
        
        _userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(_userImageView.right+4*Cell_Margin, _userImageView.top+Cell_Margin, UISCREEN_WIDTH-_userImageView.right-6*Cell_Margin, 34)];
        _userNameLabel.font = Text_Font15;
        _userNameLabel.textColor = RGB_DarkGray;
        [_userInfoView addSubview:_userNameLabel];
        _userNameLabel.text = APPDELEGATE.userInfo.name;
        
        _userTelLabel = [[UILabel alloc] initWithFrame:CGRectMake(_userNameLabel.left, _userNameLabel.bottom+Cell_Margin, _userNameLabel.width, _userNameLabel.height)];
        _userTelLabel.font = Text_Font14;
        _userTelLabel.textColor = RGB_LightGray;
        [_userInfoView addSubview:_userTelLabel];
        _userTelLabel.text = APPDELEGATE.userInfo.tel;
        
        _userInfoView.frame = CGRectMake(self.left,self.top, UISCREEN_WIDTH, _userImageView.bottom+Cell_Margin*2);
        
        //
        _recmentInfoView = [[UIView alloc] init];
        _recmentInfoView.backgroundColor = RGB_WhiteBackGround;
        [self addSubview:_recmentInfoView];
        
        _hintRecLabel = [[UILabel alloc] initWithFrame:CGRectMake(2*Cell_Margin, 2*Cell_Margin, UISCREEN_WIDTH-6*Cell_Margin, 34)];
        _hintRecLabel.text = @"谁推荐我:";
        CGSize size = [_hintRecLabel getLabelContentSizeForWidth];
        _hintRecLabel.frame = CGRectMake(2*Cell_Margin, 2*Cell_Margin, 2*Cell_Margin+size.width, 34);
        _hintRecLabel.font = Text_Font15;
        _hintRecLabel.textColor = RGB_LightGray;
        [_recmentInfoView addSubview:_hintRecLabel];
        
        _recmentMeField = [[UITextField alloc] initWithFrame:CGRectMake(_hintRecLabel.right+Cell_Margin, _hintRecLabel.top, UISCREEN_WIDTH-6*Cell_Margin-_hintRecLabel.width, 34)];
        _recmentMeField.placeholder = @"请输入推荐人的手机号";
        _recmentMeField.font = Text_Font14;
        _recmentMeField.layer.borderWidth = 0.5;
        _recmentMeField.layer.borderColor = RGB_LightGrayBackGround.CGColor;
        _recmentMeField.layer.cornerRadius = _recmentMeField.height*0.08;
        _recmentMeField.layer.masksToBounds = YES;
        [_recmentInfoView addSubview:_recmentMeField];
        
        _recmentInfoView.frame = CGRectMake(_recmentInfoView.left, _userInfoView.bottom+Cell_Margin, UISCREEN_WIDTH, _recmentMeField.bottom+2*Cell_Margin);
        
        //
        _cardInfoView = [[UIView alloc] init];
        _cardInfoView.backgroundColor = RGB_WhiteBackGround;
        [self addSubview:_cardInfoView];
        
        _cardVipLabel = [[UILabel alloc] initWithFrame:CGRectMake(2*Cell_Margin, 2*Cell_Margin, UISCREEN_WIDTH-6*Cell_Margin, 34)];
        _cardVipLabel.text = @"成为VIP";
        _cardVipLabel.font = Text_Font15;
        _cardVipLabel.textColor = RGB_LightGray;
        [_cardInfoView addSubview:_cardVipLabel];
        
//        _selCardView = [[UIView alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.3, _cardVipLabel.bottom+Cell_Margin, UISCREEN_WIDTH-2*Cell_Margin-UISCREEN_WIDTH*0.3, 34)];
//        [_cardInfoView addSubview:_selCardView];
        
        _hintCardLabel = [[RTLabel alloc] initWithFrame:CGRectMake(Cell_Margin*2,_cardVipLabel.bottom+2*Cell_Margin,  UISCREEN_WIDTH-4*Cell_Margin, 34)];
        _hintCardLabel.font = Text_Font15;
        [_cardInfoView addSubview:_hintCardLabel];
        
        _cardInfoView.frame = CGRectMake(_cardInfoView.left, _recmentInfoView.bottom+Cell_Margin, UISCREEN_WIDTH, _hintCardLabel.bottom+2*Cell_Margin);
        
        //
        _chargeInfoView = [[UIView alloc] init];
        _chargeInfoView.backgroundColor = RGB_WhiteBackGround;
        [self addSubview:_chargeInfoView];
        
        _chargeLabel = [[UILabel alloc] initWithFrame:CGRectMake(2*Cell_Margin, 2*Cell_Margin, UISCREEN_WIDTH-6*Cell_Margin, 34)];
        _chargeLabel.text = @"充值方式";
        _chargeLabel.font = Text_Font15;
        _chargeLabel.textColor = RGB_LightGray;
        [_chargeInfoView addSubview:_chargeLabel];
        
        _chargeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_chargeLabel.left, _chargeLabel.bottom+2*Cell_Margin, 60, 60)];
        _chargeImageView.contentMode = UIViewContentModeScaleAspectFit;
        _chargeImageView.layer.cornerRadius = _chargeImageView.height*0.08;
        [_chargeImageView setImage:[UIImage imageNamed:@"zhifubao"]];
        [_chargeInfoView addSubview:_chargeImageView];
        
        _chargeInfoView.frame = CGRectMake(_chargeInfoView.left, _cardInfoView.bottom+Cell_Margin, UISCREEN_WIDTH, _chargeImageView.bottom+2*Cell_Margin);
        
        //
        _payInfoView = [[UIView alloc] init];
        _payInfoView.backgroundColor = RGB(212, 212, 212);
        [self addSubview:_payInfoView];
        
        _extroInfoLabel = [[UILabel alloc] initWithFrame:CGRectMake(2*Cell_Margin, 2*Cell_Margin, UISCREEN_WIDTH-6*Cell_Margin, 34)];
        _extroInfoLabel.text = @"填写推荐用户,该用户可获得相应积分,积分可换取实物";
        _extroInfoLabel.numberOfLines = 0;
        _extroInfoLabel = [[JWTNewLabelFrame sharedInstance] newSizeFromLabel:_extroInfoLabel];
        _extroInfoLabel.font = Text_Font14;
        _extroInfoLabel.textColor = RGB_WhiteBackGround;
        [_payInfoView addSubview:_extroInfoLabel];
        
        _chargeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, _extroInfoLabel.bottom+5*Cell_Margin, UISCREEN_WIDTH*0.5, 50)];
        _chargeBtn.layer.borderWidth = 0.5f;
        _chargeBtn.layer.cornerRadius = _chargeBtn.height * 0.5;
        _chargeBtn.layer.borderColor = RGB_LightGray.CGColor;
        [_chargeBtn setTitle:@"付款" forState:UIControlStateNormal];
        [_chargeBtn setTitleColor:RGB_WhiteBackGround forState:UIControlStateNormal];
        _chargeBtn.backgroundColor = HeaderBackground_Color;
        [_payInfoView addSubview:_chargeBtn];
        _chargeBtn.center = CGPointMake(UISCREEN_WIDTH*0.5, _chargeBtn.center.y);
        
        WS(weakSelf);
        [_chargeBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
            [weakSelf alipayAction];
        }];
        
        
        _payInfoView.frame = CGRectMake(_payInfoView.left, _chargeInfoView.bottom+Cell_Margin, UISCREEN_WIDTH, _chargeBtn.bottom+2*Cell_Margin);
        
        self.frame = CGRectMake(self.left, self.top, UISCREEN_WIDTH, _payInfoView.bottom+Cell_Margin);
        
        [self reloadData];
        
    }
    return self;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_recmentMeField resignFirstResponder];
}

/**
 调用支付接口
 */
-(void) alipayAction{
    WS(weakSelf);
    
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] postJWTAlipayVIP];
    if ([_recmentMeField.text isEqualToString:APPDELEGATE.userInfo.tel]) {
        [HUD showToast:@"推荐号码不能是本登录账号"];
        return;
    }
    [HUD showUIBlockingIndicator];
    NSDictionary *dict = @{@"tokenid":APPDELEGATE.userInfo.tokenid,@"cardid":_selCardType.cardid ,@"tel":@""};
    [AFNHttpsRequest requestWithUrl:urlString WithParam:dict WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [HUD hideUIBlockingIndicator];
        NSLog(@"%@",model);
        if (model) {
//            [HUD showToast:[model objectForKey:@"message"]];
            if ([[model objectForKey:@"code"] integerValue] == 200) {
                //将签名成功字符串格式化为订单字符串，请严格按照该格式
                NSString *signedString = [model objectForKey:@"data"];
                // NOTE: 调用支付结果开始支付
                [[AlipaySDK defaultService] payOrder:signedString fromScheme:@"JWTAlipay" callback:^(NSDictionary *resultDic) {
                    NSLog(@"reslut = %@",resultDic);
                    
                    if ([resultDic[@"code"] integerValue] == 9000) {
                        [weakSelf getUserInfos];
                    }
                }];
                
            }
        }
    }];
}


/**
 请求卡类型数据
 */
-(void) reloadData{
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getJWTgetCardsType];
    [HUD showUIBlockingIndicator];
    [AFNHttpsRequest requestWithUrl:urlString WithParam:nil WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [HUD hideUIBlockingIndicator];
        if (model) {
            if ([[model objectForKey:@"code"]integerValue] == 200) {
                NSLog(@"%@",model);
                _cardTypeArray = [NSArray arrayWithArray:[model objectForKey:@"data"]];
                [self reloadCardTypeCardInfoView:_cardInfoView cardTypeArray:_cardTypeArray];
            }
        }
    }];
}

/**
 初始化年卡选择类型
 */
-(void) reloadCardTypeCardInfoView:(UIView *)cardInfoView  cardTypeArray:(NSArray *) array{
    for (JWTCardTypeView *obj in _cardInfoView.subviews) {
        if ([obj isKindOfClass:[JWTCardTypeView class]]) {
             [obj removeFromSuperview];
        }
    }
    CGFloat view_height = 44;
    NSLog(@"%@",_cardVipLabel);
    for (int i = 0; i < array.count; i++) {
        JWTCardType *cardType = [JWTCardType mj_objectWithKeyValues:[array objectAtIndex:i]];
        JWTCardTypeView *cardTypeView  = [[JWTCardTypeView alloc] initWithFrame:CGRectMake(Cell_Margin+_hintRecLabel.right, _cardVipLabel.bottom+(i+1)*Cell_Margin+i*view_height,_cardInfoView.width-_hintRecLabel.right-2*Cell_Margin, view_height)];
        cardTypeView.cardTypeLabel.text = [NSString stringWithFormat:@"%@:¥ %.2f",cardType.cardname,cardType.cardprice];
        cardTypeView.tag = i;
        if (i == 0) {
            if (_getCardType) {
                _getCardType(cardType);
            }
            _selCardType = cardType;
            [cardTypeView.cardSelBtn setImage:[UIImage imageNamed:@"card_selected"] forState:UIControlStateNormal];
            
            [_hintCardLabel setText:[NSString stringWithFormat:@"<font size=14 color=#0x364347>需要支付</font><font size=16 color=#0xf84545>%.2f</font><font size=14 color=#0x364347>元,</font><font size=14 color=#0x364347>可获得</font><font size=16 color=#0xf84545>%.2f</font><font size=14 color=#0x364347>积分</font>",cardType.cardprice,cardType.cardprice]];
           
        }
        //添加手势
        UITapGestureRecognizer *tapCardTypeView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCardTypeView:)];
        [cardTypeView addGestureRecognizer:tapCardTypeView];
        
        [_cardInfoView addSubview:cardTypeView];
    }
    
     CGFloat newHeight = (array.count+1)*Cell_Margin+array.count*view_height;
    _hintCardLabel.frame = CGRectMake(_cardVipLabel.left, _cardVipLabel.bottom+Cell_Margin*2+newHeight, UISCREEN_WIDTH-2*_cardVipLabel.left, 34);
    _cardInfoView.frame = CGRectMake(0, _recmentInfoView.bottom+Cell_Margin, UISCREEN_WIDTH, _hintCardLabel.bottom+2*Cell_Margin);
    _chargeInfoView.frame = CGRectMake(_chargeInfoView.left, _cardInfoView.bottom+Cell_Margin, _chargeInfoView.width, _chargeInfoView.height);
    
    _payInfoView.frame = CGRectMake(_payInfoView.left, _chargeInfoView.bottom+Cell_Margin, _payInfoView.width, _payInfoView.height);
    
    self.frame =  CGRectMake(self.left, self.top, UISCREEN_WIDTH, _payInfoView.bottom+Cell_Margin);
    if (_getCardTypeViewHeight) {
        _getCardTypeViewHeight(self);
    }
    
}

/**
 选择会员卡类型
 */
-(void) tapCardTypeView:(UITapGestureRecognizer *)rec{
    JWTCardType *cardType = [JWTCardType mj_objectWithKeyValues:[_cardTypeArray objectAtIndex:rec.view.tag]];
    _selCardType = cardType;
    if (_getCardType) {
        _getCardType(cardType);
    }
    for (JWTCardTypeView *obj in _cardInfoView.subviews) {
        if ([obj isKindOfClass:[JWTCardTypeView class]]) {
            if (obj.tag == rec.view.tag) {
                [obj.cardSelBtn setImage:[ UIImage imageNamed:@"card_selected"] forState:UIControlStateNormal];
                [_hintCardLabel setText:[NSString stringWithFormat:@"<font size=14 color=#0x364347>需要支付</font><font size=16 color=#0xf84545>%.2f</font><font size=14 color=#0x364347>元,</font><font size=14 color=#0x364347>可获得</font><font size=16 color=#0xf84545>%.2f</font><font size=14 color=#0x364347>积分</font>",cardType.cardprice,cardType.cardprice]];
            }else{
                [obj.cardSelBtn setImage:[ UIImage imageNamed:@"card_normal"] forState:UIControlStateNormal];
            }
        }
    }
}


#pragma mark - 获取用户信息
- (void)getUserInfos {
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getUserDetailInfoWithActionUserMessage];
    [HUD showUIBlockingIndicator];
    [AFNHttpsRequest requestWithUrl:urlString WithParam:nil WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [HUD hideUIBlockingIndicator];
        if (model) {
            if ([[model objectForKey:@"code"]integerValue] == 200) {
                NSLog(@"%@",[model objectForKey:@"data"]);
                
                UITabBarController *tabbarVC = (UITabBarController *)[[UIApplication sharedApplication].keyWindow rootViewController];
                UINavigationController *nav = tabbarVC.selectedViewController;
                
                [nav popViewControllerAnimated:YES];
            }
        } else {
            [HUD showToast:error.localizedDescription];
        }
    }];
}

@end
